package pub.wkq.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import pub.wkq.common.exception.CustomException;
import pub.wkq.common.result.ResponseStatusEnum;

import java.io.IOException;
import java.util.List;

public class SerializationUtils {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    // 序列化对象
    public static String serializeObject(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new CustomException(ResponseStatusEnum.SYSTEM_SERIALIZE_ERROR);
        }
    }

    // 反序列化对象
    public static <T> T deserializeObject(String json, Class<T> valueType) {
//        return objectMapper.readValue(json, valueType);
        try {
            return objectMapper.readValue(json, valueType);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new CustomException(ResponseStatusEnum.SYSTEM_DESERIALIZE_ERROR);
        }
    }

    // 序列化列表
    public static String serializeList(List<?> list) throws JsonProcessingException {
        return objectMapper.writeValueAsString(list);
    }

    // 反序列化列表
    public static <T> List<T> deserializeList(String json, Class<T> valueType) throws IOException {
        return objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(List.class, valueType));
    }

}
